﻿using ProjectScheduling.daos;
using ProjectScheduling.models;
using SqlSugar;
using System.Data;

namespace ProjectScheduling
{
    /// <summary>
    /// 选择可用的用户信息
    /// </summary>
    public partial class CheckUsedStaffForm : Form
    {
        public static readonly CheckUsedStaffForm b = new();
        private List<Staff> _usedStaffs = [];
        private List<Staff> _staffs = [];
        public Action<List<(int id, string name)>>? action_checked;
        /// <summary>
        /// 根据开始时间结束时间获取员工信息
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="project_id"></param>
        public void GetStaffByStartEnd(DateTime start, DateTime end, int project_id)
        {
            var table = ProjectStaffDao.Base.ToTable(
                "SELECT DISTINCT b.UserId FROM Projects a INNER JOIN ProjectStaff b ON a.Id=b.ProjectId WHERE a.State IN (2,4) AND @end>=a.FromDate AND @start<=a.ToDate AND  a.Id<>@project_id",
                ("@start", start), ("@end", end), ("@project_id", project_id)
            );
            var ids = table.Rows.Cast<DataRow>().Select(it => Convert.ToInt32(it["UserId"]?.ToString() ?? ""));
            UsedStaffs = StaffDao.Base.FindAll(it => !ids.Contains(it.Id));
        }
        public void CheckedUser(List<int> userId)
        {
            if (userId.Count == 0)
            {
                lst_usedStaffs.ClearSelected();
            }
            if (UsedStaffs != null && UsedStaffs.Count > 0)
            {
                for (int i = 0; i < UsedStaffs.Count; i++)
                {
                    lst_usedStaffs.SetSelected(i, userId.Contains(UsedStaffs[i].Id));
                }
            }
        }
        /// <summary>
        /// 根据开始结束时间 获取推荐的员工列表（与当前时间段有冲突的）
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        public void GetProposeStaffByStartEnd(DateTime start, DateTime end)
        {
            lst_otherStaffs.Items.Clear();
            var totaldays = (end - start).Days + ((end - start).Hours > 0 ? 1 : 0);
            var states = new List<Enum_ProjectState> { Enum_ProjectState.已排期, Enum_ProjectState.实施中 };
            var ps = ProjectDao.Base.FindAll(it => states.Contains(it.State) && end > it.FromDate && start < it.ToDate).Where(it => !(it.FromDate <= start && it.ToDate >= end)).ToList();
            var lst1 = ps.Where(it => it != null && it.StaffsList != null).SelectMany(item => item.StaffsList?.Select(it => (user_id: it.UserId, user_name: it.UserName, start: item.FromDate, end: item.ToDate)) ?? []).ToList();
            var items = new List<(int days, string str)>();
            foreach (var item in lst1.GroupBy(it => new { it.user_id, it.user_name }))
            {
                static DateTime today(DateTime dt) => DateTime.Parse(dt.ToString("yyyy-MM-dd"));
                var its = item.Select(it => new
                {
                    start = it.start < start ? start : it.start,
                    end = it.end > end ? end : it.end
                }).Where(it => today(it.start) != today(start) || today(it.end) != today(end)).OrderBy(it => it.start).ToList();
                var lstr = string.Join("、", its.Select(i => $"{i.start:MM-dd}~{i.end:MM-dd}"));
                var days = its.Sum(i => (i.end - i.start).Days + ((i.end - i.start).Hours > 0 ? 1 : 0));
                if (its.Count > 0 && days < totaldays)
                    items.Add((days, $"{item.Key.user_name}-（{lstr}）有排期，共{days}天"));
            }
            foreach (var (_, str) in items.OrderBy(it => it.days))
            {
                lst_otherStaffs.Items.Add(str);
            }
        }
        public CheckUsedStaffForm()
        {
            InitializeComponent();
        }
        private void setListValue(ListBox box, List<Staff> staffs)
        {
            box.Items.Clear();
            box.Items.AddRange([.. staffs]);
        }

        private void btn_check_Click(object sender, EventArgs e)
        {
            var indexs = lst_usedStaffs.SelectedIndices.Cast<int>().ToList();
            var _checkedUsers = UsedStaffs.Where((_, index) => indexs.Contains(index)).Select(it => (it.Id, it.TrueName ?? "")).ToList();
            action_checked?.Invoke(_checkedUsers);
            Close();
        }

        private void lst_usedStaffs_SelectedIndexChanged(object sender, EventArgs e)
        {
            lb_used.Text = $"可选择员工（{lst_usedStaffs.SelectedItems.Count}/{lst_usedStaffs.Items.Count}）";
        }

        /// <summary>
        /// 可用的员工信息
        /// </summary>
        public List<Staff> UsedStaffs
        {
            get
            {
                return _usedStaffs;
            }
            set
            {
                setListValue(lst_usedStaffs, _usedStaffs = value);
            }
        }
        public List<Staff> Staffs
        {
            get
            {
                return _staffs;
            }
            set
            {
                setListValue(lst_otherStaffs, _staffs = value);
            }
        }
    }
}
